package com.example.forum.controller;

import com.example.forum.dto.TokenCreate;
import com.example.forum.entity.Token;
import com.example.forum.entity.User;
import com.example.forum.interceptor.TokenContext;
import com.example.forum.mapper.TokenMapper;
import com.example.forum.mapper.UserMapper;
import com.example.forum.util.JsonResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
public class TokenController {

    @Resource
    TokenMapper tokenMapper;
    @Resource
    UserMapper userMapper;

    @PostMapping("/api/token/create")
    public JsonResult<Object> create(@Valid TokenCreate tokenCreate) {
        //登陆操作，账户密码正确则生成token，储存token
        //查user表，验证密码,得到userID
        //验证成功生成随机md5 存到token表
        String username = tokenCreate.getUsername();
        String password = tokenCreate.getPassword();
        User userLogin = userMapper.selectUser(username);
        if (userLogin == null) {
            return new JsonResult<>("error", "账户不存在");
        }
        if (!(userLogin.getPassword()).equals(password)) {
            System.out.println("登录失败");
            return new JsonResult<>("error", "账号或密码错误");
        } else {
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            System.out.println(token);
            Integer id = userMapper.selectUser(username).getId();
            Token tokenInsert = Token.builder().userId(id).token(token).build();
            //此处为直接新增token。bug 理论上：新增前应该把重复或者即将重复的userId记录先删除（查询+删除+新增）
            int a = tokenMapper.insert(tokenInsert);
            if (a == 1) {
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
//                Token token1=Token.builder().id(1).token(token).build();
                TokenContext.setToken(tokenInsert);
                System.out.println(tokenInsert);
                System.out.println(12340);
                System.out.println(TokenContext.getToken());
                //更新登录时间
                try {
                    Date date=new Date();
                    userMapper.loginUpdate(date,username);
                } catch (Exception e) {
                    System.out.println(9999999);
                    throw new RuntimeException(e);
                }
                return new JsonResult<>("", data);
            } else {
                return new JsonResult<>("未知错误error", "token新增失败");
            }
        }
    }
    @GetMapping("/api/token/delete")
    public JsonResult<Object> delete(){
//        //获取上下文的用户，根据用户查找token，然后删除
//        String username=UserContext.getUser().getUsername();
//        if(username==null){
//            throw  new RuntimeException("未知错误，根据userid查不到username");
//        }
        //试试直接获取上下文token,如果得到则删除token
        System.out.println(TokenContext.getToken());
        String token=TokenContext.getToken().getToken();

        if(token==null){
            return new JsonResult<>("error","删除失败，找不到token");
        }
        else{
            int i=tokenMapper.delete(token);
            if (!(i==1)){
                return new JsonResult<>("error","token删除失败，");
            }else{
                Map<String,String>data=new HashMap<>();
                data.put("","删除成功");
                return new JsonResult<>("Success",data);
            }

        }

    }
}
